package com.lhy.mymall.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author: lhy-卢辉宇
 * @date: 2023/7/17 11:34
 * @description:
 */
@Configuration
@EnableCaching
public class RedisConfig {

    @Resource
    private RedisConnectionFactory connectionFactory;

    /**
     * 配置redis的序列化
     *
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        //1.创建RedisTemplated对象
        RedisTemplate<Object, Object> template = new RedisTemplate<>();

        //2.设置连接工厂
        template.setConnectionFactory(connectionFactory);

        //3.创建JSON序列化工具
        FastJson2JsonRedisSerializer jsonRedisSerializer = new FastJson2JsonRedisSerializer(Object.class);

        //4.设置key的序列化
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        //5.设置value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        //6.返回
        return template;
    }

    /**
     * 缓存的配置
     *
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager() {

        RedisCacheWriter redisCacheWriter = RedisCacheWriter
                .lockingRedisCacheWriter(connectionFactory);
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        //缓存超时时间
        cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));

        RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,
                cacheConfiguration);
        return redisCacheManager;
    }

}
